package com.woniu108.product.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu108.carService.commos.dto.AdminInfoDto;
import com.woniu108.carService.commos.dto.ProductActiveDto;
import com.woniu108.carService.commos.dto.UserInfoDto;
import com.woniu108.carService.commos.exception.admin.AdminException;
import com.woniu108.carService.commos.exception.admin.AdminExceptionCode;
import com.woniu108.carService.commos.exception.produnt.ProductException;
import com.woniu108.carService.commos.exception.produnt.ProductExceptionCode;
import com.woniu108.product.mapper.ProductItemMapper;
import com.woniu108.product.model.ProductItem;
import com.woniu108.product.param.DeleteActiveParam;
import com.woniu108.product.service.ProductActiveService;
import org.springframework.stereotype.Service;
import com.woniu108.product.client.PersonClient;
import com.woniu108.product.mapper.ProductActiveMapper;
import com.woniu108.product.model.ProductActive;
import com.woniu108.product.param.InsertActiveParam;
import com.woniu108.product.param.UpdateActiveParam;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商品活动表 服务实现类
 * </p>
 *
 * @author yanxi
 * @since 2024-05-23
 */
@Service
public class ProductActiveServiceImpl extends ServiceImpl<ProductActiveMapper, ProductActive> implements ProductActiveService {
    @Resource
    private PersonClient personClient;
    @Resource
    private ProductActiveMapper productActiveMapper;

    @Resource
    private ProductItemMapper productItemMapper;
    /**
     * 判断管理员
     */
    private void isAdmin(String adminId) {
        // 检查 adminId 是否为 null
        if (adminId == null) {
            throw new AdminException(AdminExceptionCode.ADMIN_ID_NULL);
        }
        // 判断管理员权限
        AdminInfoDto adminInfo = personClient.getByAdminId(adminId).getData();
        if (adminInfo == null) {
            throw new AdminException(AdminExceptionCode.ADMIN_NOT_HAVE);
        }
        if (adminInfo.getAdminRoleId() != 1) {
            throw new AdminException(AdminExceptionCode.ADMIN_NOT_PERMISSION);
        }
    }
    /**
     * 判断用户
     */
    private void isUser(String userId) {
        // 检查 userId 是否为 null
        if (userId == null) {
            throw new AdminException(AdminExceptionCode.ADMIN_ID_NULL);
        }
        // 判断用户
        UserInfoDto userInfo = personClient.getByUserId(userId).getData();
        if (userInfo == null) {
            throw new AdminException(AdminExceptionCode.ADMIN_NOT_HAVE);
        }
    }

    @Override
    public List<ProductActiveDto> findAllActive(Integer activeId) {
        QueryWrapper<ProductActive> wrapper = new QueryWrapper<>();
        if (activeId!=null){
            wrapper.eq("active_id",activeId);
        }
        //筛选符合时间的
        LocalDateTime now = LocalDateTime.now();

        // 删除结束时间在当前时间之前的记录
        QueryWrapper<ProductActive> deleteWrapper = new QueryWrapper<>();
        deleteWrapper.lt("end_time", now);
        productActiveMapper.delete(deleteWrapper);

        List<ProductActive> list = productActiveMapper.selectList(wrapper);

        List<ProductActiveDto> dtos =new ArrayList<>();
        for (ProductActive active:list){
            ProductActiveDto dto = BeanUtil.toBean(active, ProductActiveDto.class);
            ProductItem item = productItemMapper.selectById(dto.getPItemId());
            dto.setPName(item.getPName());
            dtos.add(dto);
        }
        return dtos;
    }

    @Override
    public List<ProductActiveDto> findAllActiveByItemId(Integer pItemId) {
        QueryWrapper<ProductActive> wrapper = new QueryWrapper<>();
        if (pItemId!=null){
            wrapper.eq("p_item_id",pItemId);
        }
        //筛选符合时间的
        LocalDateTime now = LocalDateTime.now();

        // 删除结束时间在当前时间之前的记录
        QueryWrapper<ProductActive> deleteWrapper = new QueryWrapper<>();
        deleteWrapper.lt("end_time", now);
        productActiveMapper.delete(deleteWrapper);

        List<ProductActive> list = productActiveMapper.selectList(wrapper);
        List<ProductActiveDto> dtos =new ArrayList<>();
        for (ProductActive active:list){
            ProductActiveDto dto = BeanUtil.toBean(active, ProductActiveDto.class);
            ProductItem item = productItemMapper.selectById(dto.getPItemId());
            dto.setPName(item.getPName());
            dtos.add(dto);
        }
        return dtos;
    }

    @Override
    public Boolean insertActive(InsertActiveParam param) {
        //判断管理员
        isAdmin(param.getAdminId());
        //查询是否存在该商品的折扣
        QueryWrapper<ProductActive> wrapper = new QueryWrapper<>();
        wrapper.eq("p_item_id",param.getPItemId());
        ProductActive selectOne = productActiveMapper.selectOne(wrapper);
        //判断是否存在和时间是否正确
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        if (selectOne!=null){
            if (selectOne.getEndTime().isBefore(now)){
                // 如果结束时间在当前时间之前，可以删除旧的折扣
                productActiveMapper.deleteById(selectOne);
            }
                throw new ProductException(ProductExceptionCode.PRODUCT_ACTIVE_HAVE);
        }
        // 创建新的折扣活动
        ProductActive newActive = new ProductActive();
        newActive.setPItemId(param.getPItemId());
        newActive.setStartTime(param.getStartTime());
        newActive.setEndTime(param.getEndTime());
        newActive.setCutDownPercent(param.getCutDownPercent());
        // 插入新的折扣活动
        int result = productActiveMapper.insert(newActive);
        return result > 0;
    }

    @Override
    public Boolean updateActive(UpdateActiveParam param) {
        // 判断管理员权限
        isAdmin(param.getAdminId());

        // 查询是否存在该活动
        ProductActive active = productActiveMapper.selectById(param.getActiveId());

        // 如果活动不存在，抛出异常
        if (active == null) {
            throw new ProductException(ProductExceptionCode.PRODUCT_ACTIVE_NOT_FOUND);
        }

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 更新开始时间
        if (param.getStartTime() != null) {
            if (param.getStartTime().isBefore(now)) {
                throw new ProductException(ProductExceptionCode.INVALID_START_TIME);
            }
            active.setStartTime(param.getStartTime());
        }

        // 更新结束时间
        if (param.getEndTime() != null) {
            // 如果提供了新的开始时间，使用它进行比较，否则使用现有的开始时间
            LocalDateTime effectiveStartTime = param.getStartTime() != null ? param.getStartTime() : active.getStartTime();
            if (param.getEndTime().isBefore(now)) {
                throw new ProductException(ProductExceptionCode.INVALID_END_TIME_BEFORE_NOW);
            }
            if (param.getEndTime().isBefore(effectiveStartTime)) {
                throw new ProductException(ProductExceptionCode.INVALID_END_TIME_BEFORE_START);
            }
            active.setEndTime(param.getEndTime());
        }

        // 更新折扣
        if (param.getCutDownPercent() != null) {
            active.setCutDownPercent(param.getCutDownPercent());
        }

        // 更新数据库中的活动信息
        int result = productActiveMapper.updateById(active);

        return result > 0;
    }

    @Override
    public Boolean deleteActive(DeleteActiveParam param) {
        // 判断管理员权限
        isAdmin(param.getAdminId());
        int i = productActiveMapper.deleteById(param.getActiveId());
        return i>0;
    }
}
